package com.gscitysfy.cus.drain.modules.command.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.google.common.base.Joiner;
import com.google.common.base.Splitter;
import com.gscitysfy.cus.drain.config.BusinessException;
import com.gscitysfy.cus.drain.modules.command.convert.InstructTaskConvert;
import com.gscitysfy.cus.drain.modules.command.dto.InstructTaskDto;
import com.gscitysfy.cus.drain.modules.command.entity.InstructCar;
import com.gscitysfy.cus.drain.modules.command.entity.InstructTeam;
import com.gscitysfy.cus.drain.modules.command.mapper.InstructCarMapper;
import com.gscitysfy.cus.drain.modules.command.mapper.InstructTeamMapper;
import com.gscitysfy.cus.drain.modules.command.service.IAppletService;
import com.gscitysfy.cus.drain.modules.command.vo.AppletQuery;
import com.gscitysfy.cus.drain.modules.resource.entity.ResourceCar;
import com.gscitysfy.cus.drain.modules.resource.entity.ResourceTeam;
import com.gscitysfy.cus.drain.modules.resource.mapper.ResourceCarMapper;
import com.gscitysfy.cus.drain.modules.resource.mapper.ResourceTeamMapper;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

/**
 * @Author jiang_wen
 * @Date 2022/10/25 15:27
 * @Description TODO
 */
@AllArgsConstructor
@Service
public class AppletServiceImpl implements IAppletService {

    private final ResourceCarMapper resourceCarMapper;
    private final ResourceTeamMapper resourceTeamMapper;
    private final InstructCarMapper instructCarMapper;
    private final InstructTeamMapper instructTeamMapper;

    private final InstructTaskConvert instructTaskConvert;


    @Override
    public List<InstructTaskDto> list(AppletQuery query) {
        List<InstructTaskDto> instructTaskDtoList = new ArrayList<>();
        if (StringUtils.isEmpty(query.getPhone())) {
            throw new BusinessException("绑定手机号不能为空");
        }
        //1、基于应急车辆
        Optional<ResourceCar> optionalResourceCar = resourceCarMapper.getByPhone(query.getPhone());
        if (optionalResourceCar.isPresent()) {
            ResourceCar resourceCar = optionalResourceCar.get();
            LambdaQueryWrapper<InstructCar> instructCarWrapper = Wrappers.lambdaQuery();
            instructCarWrapper.eq(InstructCar::getCarId, resourceCar.getCmKid());
            if (StringUtils.isNotEmpty(query.getStatus())) {
                instructCarWrapper.eq(InstructCar::getStatus, query.getStatus());
            }
            if (Objects.nonNull(query.getCloseFlag())) {
                instructCarWrapper.eq(InstructCar::getCloseFlag, query.getCloseFlag());
            }
            instructCarWrapper.eq(InstructCar::getCmUsable, query.getCmUsable());
            List<InstructCar> instructCarList = instructCarMapper.selectList(instructCarWrapper);
            List<InstructTaskDto> instructTaskCarDtoList = instructTaskConvert.toCarDtoList(instructCarList);
            instructTaskDtoList.addAll(instructTaskCarDtoList);
        }
        //2、基于应急队伍
        Optional<ResourceTeam> optionalResourceTeam = resourceTeamMapper.getByPhone(query.getPhone());
        if (optionalResourceTeam.isPresent()) {
            ResourceTeam resourceTeam = optionalResourceTeam.get();
            LambdaQueryWrapper<InstructTeam> instructTeamWrapper = Wrappers.lambdaQuery();
            instructTeamWrapper.eq(InstructTeam::getTeamId, resourceTeam.getCmKid());
            if (StringUtils.isNotEmpty(query.getStatus())) {
                instructTeamWrapper.eq(InstructTeam::getStatus, query.getStatus());
            }
            if (Objects.nonNull(query.getCloseFlag())) {
                instructTeamWrapper.eq(InstructTeam::getCloseFlag, query.getCloseFlag());
            }
            instructTeamWrapper.eq(InstructTeam::getCmUsable, query.getCmUsable());
            List<InstructTeam> instructTeamList = instructTeamMapper.selectList(instructTeamWrapper);
            List<InstructTaskDto> instructTaskTeamDtoList = instructTaskConvert.toTeamDtoList(instructTeamList);
            instructTaskDtoList.addAll(instructTaskTeamDtoList);
        }
        return instructTaskDtoList;
    }

    @Override
    public InstructTaskDto getById(Long cmKid) {
        InstructCar instructCar = instructCarMapper.selectById(cmKid);
        if (Objects.nonNull(instructCar)) {
            return instructTaskConvert.toCarDto(instructCar);
        } else {
            InstructTeam instructTeam = instructTeamMapper.selectById(cmKid);
            return instructTaskConvert.toTeamDto(instructTeam);
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void arrive(Long cmKid) {
        InstructCar instructCar = instructCarMapper.selectById(cmKid);
        if (Objects.nonNull(instructCar)) {
            instructCar.setArriveFlag(true);
            instructCar.setArriveTime(LocalDateTime.now());
            instructCarMapper.updateById(instructCar);
        } else {
            InstructTeam instructTeam = instructTeamMapper.selectById(cmKid);
            if (Objects.nonNull(instructTeam)) {
                instructTeam.setArriveFlag(true);
                instructTeam.setArriveTime(LocalDateTime.now());
                instructTeamMapper.updateById(instructTeam);
            }
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void suspend(Long cmKid) {
        InstructCar instructCar = instructCarMapper.selectById(cmKid);
        if (Objects.nonNull(instructCar)) {
            //终止或者继续任务可以添加时间戳
            String now = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(LocalDateTime.now());
            String taskTimestamp = instructCar.getTaskTimestamp();
            List<String> taskTimestampList = new ArrayList<>(Splitter.on(",").splitToList(taskTimestamp));
            taskTimestampList.add(now);
            instructCar.setTaskTimestamp(Joiner.on(",").join(taskTimestampList));
            instructCar.setSuspendFlag(!instructCar.getSuspendFlag());
            instructCarMapper.updateById(instructCar);
        } else {
            InstructTeam instructTeam = instructTeamMapper.selectById(cmKid);
            if (Objects.nonNull(instructTeam)) {
                //终止或者继续任务可以添加时间戳
                String now = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(LocalDateTime.now());
                String taskTimestamp = instructTeam.getTaskTimestamp();
                List<String> taskTimestampList = new ArrayList<>(Splitter.on(",").splitToList(taskTimestamp));
                taskTimestampList.add(now);
                instructTeam.setTaskTimestamp(Joiner.on(",").join(taskTimestampList));
                instructTeam.setSuspendFlag(!instructTeam.getSuspendFlag());
                instructTeamMapper.updateById(instructTeam);
            }
        }
    }

    @Transactional(rollbackFor = Throwable.class)
    @Override
    public void update(InstructTaskDto instructTaskDto) {
        Long cmKid = instructTaskDto.getCmKid();
        InstructCar instructCar = instructCarMapper.selectById(cmKid);
        if (Objects.nonNull(instructCar)) {
            if (Objects.nonNull(instructTaskDto.getCloseFlag())) {
                //关闭任务可以添加时间戳
                String now = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(LocalDateTime.now());
                String taskTimestamp = instructCar.getTaskTimestamp();
                List<String> taskTimestampList = new ArrayList<>(Splitter.on(",").splitToList(taskTimestamp));
                taskTimestampList.add(now);
                instructCar.setTaskTimestamp(Joiner.on(",").join(taskTimestampList));
                instructCar.setCloseFlag(instructTaskDto.getCloseFlag());
            }
            if (StringUtils.isNotEmpty(instructTaskDto.getStatus())) {
                //接收任务可以添加开始时间戳
                if (StringUtils.equals(instructTaskDto.getStatus(), "ACCEPT")) {
                    String now = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(LocalDateTime.now());
                    instructCar.setTaskTimestamp(now);
                }
                instructCar.setStatus(instructTaskDto.getStatus());
            }
            if (Objects.nonNull(instructTaskDto.getTimer())) {
                instructCar.setTimer(instructTaskDto.getTimer());
            }
            if (StringUtils.isNotEmpty(instructTaskDto.getProblemDetail())) {
                instructCar.setProblemDetail(instructTaskDto.getProblemDetail());
            }
            if (Objects.nonNull(instructTaskDto.getFileId())) {
                instructCar.setFileId(instructTaskDto.getFileId());
            }
            instructCarMapper.updateById(instructCar);
        } else {
            InstructTeam instructTeam = instructTeamMapper.selectById(cmKid);
            if (Objects.nonNull(instructTeam)) {
                if (Objects.nonNull(instructTaskDto.getCloseFlag())) {
                    //关闭任务可以添加时间戳
                    String now = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(LocalDateTime.now());
                    String taskTimestamp = instructTeam.getTaskTimestamp();
                    List<String> taskTimestampList = new ArrayList<>(Splitter.on(",").splitToList(taskTimestamp));
                    taskTimestampList.add(now);
                    instructTeam.setTaskTimestamp(Joiner.on(",").join(taskTimestampList));
                    instructTeam.setCloseFlag(instructTaskDto.getCloseFlag());
                }
                if (StringUtils.isNotEmpty(instructTaskDto.getStatus())) {
                    //接收任务可以添加开始时间戳
                    if (StringUtils.equals(instructTaskDto.getStatus(), "ACCEPT")) {
                        String now = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss").withZone(ZoneId.systemDefault()).format(LocalDateTime.now());
                        instructTeam.setTaskTimestamp(now);
                    }
                    instructTeam.setStatus(instructTaskDto.getStatus());
                }
                if (Objects.nonNull(instructTaskDto.getTimer())) {
                    instructTeam.setTimer(instructTaskDto.getTimer());
                }
                if (StringUtils.isNotEmpty(instructTaskDto.getProblemDetail())) {
                    instructTeam.setProblemDetail(instructTaskDto.getProblemDetail());
                }
                if (Objects.nonNull(instructTaskDto.getFileId())) {
                    instructTeam.setFileId(instructTaskDto.getFileId());
                }
                instructTeamMapper.updateById(instructTeam);
            }
        }
    }
}
